package cn.lrwjz.androidguide.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import java.util.List;

import cn.lrwjz.androidguide.R;
import cn.lrwjz.androidguide.model.RecyclerItem;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    private List<RecyclerItem> items;
    private OnItemClickListener listener;
    private boolean isStaggeredGrid;

    public RecyclerAdapter(List<RecyclerItem> items, boolean isStaggeredGrid) {
        this.items = items;
        this.isStaggeredGrid = isStaggeredGrid;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_recycler, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        RecyclerItem item = items.get(position);
        
        // 设置数据
        holder.imageView.setImageResource(item.getImageResId());
        holder.titleText.setText(item.getTitle());
        holder.descriptionText.setText(item.getDescription());
        
        // 只在瀑布流布局时设置随机高度
        if (isStaggeredGrid) {
            ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
            if (lp instanceof StaggeredGridLayoutManager.LayoutParams) {
                lp.height = item.getHeight();
                holder.itemView.setLayoutParams(lp);
            }
        }

        // 设置点击事件
        if (listener != null) {
            holder.itemView.setOnClickListener(v -> 
                listener.onItemClick(item, position));
        }
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(RecyclerItem item, int position);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView titleText;
        TextView descriptionText;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView);
            titleText = itemView.findViewById(R.id.titleText);
            descriptionText = itemView.findViewById(R.id.descriptionText);
        }
    }
} 